/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.chipchip.database.tables;

import com.chipchip.database.DBManager;
import com.chipchip.database.objects.DOItem;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;


/**
 *
 * @author Tri
 */
public class DTItem {
    public static final String TABLE_NAME = "Item";
    private static DTItem instance = null;
    public static DTItem sharedInstance() {
        if(instance == null) {
            instance = new DTItem();
        }
        return instance;
    }
    MongoOperations m_mongoOperations;
    
    private DTItem() {
        m_mongoOperations = DBManager.sharedInstance().mongoOperations();
    }
    
    public void insert(DOItem item) {
        m_mongoOperations.save(item, TABLE_NAME);
    }
    
    public boolean update(DOItem item) {
        Query query = new Query();
        query.addCriteria(Criteria.where(DOItem.KEY_ITEM_ID).is(item.getID()));
        DOItem resultQuery = m_mongoOperations.findOne(query, DOItem.class);
        if(resultQuery != null) {
            Update update = new Update();
            update.set(DOItem.KEY_COST, item.cost);
            update.set(DOItem.KEY_DES, item.desc);
            update.set(DOItem.KEY_INGAME_ITEM, item.isIngameItem());
            update.set(DOItem.KEY_ITEM_URL, item.itemURL);
            update.set(DOItem.KEY_NAME, item.name);
            
            m_mongoOperations.updateFirst(query, update, DOItem.class);
            return true;
        }
        return false;
    }
    
    public boolean delete(String itemID) {
        Query query = new Query();
        query.addCriteria(Criteria.where(DOItem.KEY_ITEM_ID).is(itemID));
        DOItem item = m_mongoOperations.findOne(query, DOItem.class);
        if(item != null) {
            m_mongoOperations.remove(item);
            return true;
        }
        return false;
    }
    
    public DOItem getItem(String itemID) {
        DOItem item = null;
        Query query = new  Query();
        query.addCriteria(Criteria.where(DOItem.KEY_ITEM_ID).is(itemID));
        item = m_mongoOperations.findOne(query, DOItem.class);
        return item;
    }
}
